import matplotlib.pyplot as plt
import pandas as pd
import os

def read_and_plot(file_name, ax, title, xlabel='x', ylabel='y', ylim=(0, 2)):
    """Read data from CSV and plot on the given axis."""
    if os.path.exists(file_name):
        data = pd.read_csv(file_name, header=None)
        x = data[0].tolist()
        y = data[1].tolist()
        ax.plot(x, y, label=title, linewidth=2.0)
        ax.set_title(title, fontsize=10)
        ax.set_xlabel(xlabel, fontsize=8)
        ax.set_ylabel(ylabel, fontsize=8)
        ax.set_ylim(*ylim)
        ax.tick_params(axis='both', which='major', labelsize=8)
        ax.grid(alpha=0.5, linestyle='--')
    else:
        print(f"Warning: {file_name} does not exist.")

def plot_truncated_functions(degree, max_knots, output_file):
    """Plot truncated functions for a given degree."""
    # Ensure the output directory exists
    output_dir = os.path.dirname(output_file)
    if output_dir and not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    fig, axs = plt.subplots(max_knots, max_knots, figsize=(12, 10), squeeze=False)
    plt.suptitle(f'Truncated Functions n={degree}', fontsize=16, fontweight='bold')

    for i in range(max_knots):
        for j in range(i, max_knots):
            file_name = f"data_F_n{degree}_{i}_{j}.csv"
            ax = axs[j, i]  # Access subplot by row and column
            title = f'$B_{{{i}}}^{{{j}}}(x)$'
            read_and_plot(file_name, ax, title)

    # Adjust subplot spacing
    plt.tight_layout(rect=[0, 0, 1, 0.96])
    plt.subplots_adjust(hspace=0.4, wspace=0.4)  # Add spacing between plots
    
    # Save the figure
    plt.savefig(output_file, dpi=300, bbox_inches='tight')
    print(f"Plot saved to {output_file}")
    plt.show()
    plt.close()
# Plot n=1
plot_truncated_functions(degree=1, max_knots=3, output_file='../figure/F1.png')

# Plot n=2
plot_truncated_functions(degree=2, max_knots=4, output_file='../figure/F2.png')



